import { createSlice } from '@reduxjs/toolkit' //用于创建reducer

//创建redux
const tabSlice = createSlice({
    name:'tab',
    initialState:{
        //菜单栏初始状态是否收起
        isCollapse: false,
        tabList: [
            {
                path: '/home',
                name: 'home',
                label:'首页'
            }
        ],
        currentMenu: {
            path: '/home',
            name: 'home',
            label:'首页'
        }
    },
    //用于修改状态
    reducers: {
        collapseMenu: state => {
            state.isCollapse = !state.isCollapse
        },
        selectMenuList: (state, { payload: val} ) => {
            state.currentMenu = val
            //如果已经存在的Tag就不需要添加
            const result = state.tabList.findIndex(item => item.name === val.name)
            if(result === -1) {
                state.tabList.push(val)
            }
        },
        closeTab: (state, { payload: val }) => {
            let res = state.tabList.findIndex(item => item.name === val.name)
            //删除当前Tab
            state.tabList.splice(res, 1)
        },
        setCurrentMenu: (state, { payload: val }) => {
            state.currentMenu = val
        }
    }
})

export const { collapseMenu, selectMenuList, closeTab, setCurrentMenu } = tabSlice.actions //actions属性会包含所有reducers的方法
export default tabSlice.reducer